import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:grint/bloc/auth_cubit.dart';
import 'package:grint/bloc/follow_cubit.dart';
import 'package:grint/bloc/chat_cubit.dart';
import 'package:grint/constant/colors.dart';
import 'package:grint/constant/icon_font.dart';
import 'package:grint/data/user_data.dart';
import 'package:grint/data/chat_data.dart';
import 'package:grint/entity/user.dart';
import 'package:grint/entity/chat_message.dart';
import 'package:grint/widget/my_text.dart';
import 'package:grint/widget/no_data.dart';

class _ConversationWithUser {
  final ChatConversation conversation;
  final User user;
  final String? lastMessage;

  _ConversationWithUser({
    required this.conversation,
    required this.user,
    this.lastMessage,
  });
}

class MessagePage extends StatefulWidget {
  const MessagePage({super.key});

  @override
  State<MessagePage> createState() => _MessagePageState();
}

class _MessagePageState extends State<MessagePage> {
  final PageController _yemianKongzhi = PageController();
  int _dangqianYemian = 0;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadChatData();
    });
  }

  @override
  void dispose() {
    _yemianKongzhi.dispose();
    super.dispose();
  }

  void _loadChatData() {
    final authState = context.read<AuthCubit>().state;
    if (authState.isLoggedIn && authState.currentUser != null) {
      context.read<ChatCubit>().loadUserConversations(
        authState.currentUser!.id,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<AuthCubit, AuthState>(
      builder: (context, authState) {
        return Scaffold(
          body: Stack(
            children: [
              Positioned.fill(
                child: Container(
                  decoration: const BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage('assets/images/commonBg.png'),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
              ),

              SafeArea(
                bottom: false,
                child: Column(
                  children: [
                    GestureDetector(
                      onTap: () {
                        if (authState.isLoggedIn) {
                          context.push('/message/chat');
                        } else {
                          context.push('/auth');
                        }
                      },
                      child: Padding(
                        padding: EdgeInsets.only(bottom: 16.h),
                        child: MyText(
                          text: 'Chat',
                          type: TextType.rubik,
                          fontSize: 28.sp,
                          fontWeight: FontWeight.bold,
                          color: Colors.black,
                          textAlign: TextAlign.center,
                        ),
                      ),
                    ),

                    Expanded(
                      child: Container(
                        margin: EdgeInsets.symmetric(horizontal: 16.w),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(24.r),
                        ),
                        child:
                            authState.isLoggedIn
                                ? _chuangjianYidengluNeirong()
                                : _chuangjianWeidengluNeirong(),
                      ),
                    ),

                    SizedBox(height: 56.h),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _chuangjianYidengluNeirong() {
    return Column(
      children: [
        Padding(
          padding: EdgeInsets.symmetric(vertical: 12.h),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              _chuangjianBiaoqian("Message", 0),
              SizedBox(width: 32.w),
              _chuangjianBiaoqian("Follow", 1),
            ],
          ),
        ),

        Expanded(
          child: PageView(
            controller: _yemianKongzhi,
            onPageChanged: (index) {
              setState(() {
                _dangqianYemian = index;
              });
            },
            children: [_chuangjianXiaoxiLiebiao(), _chuangjianGuanzhuLiebiao()],
          ),
        ),
      ],
    );
  }

  Widget _chuangjianWeidengluNeirong() {
    return Center(
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 32.w, vertical: 80.h),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              IconFontIcons.iconChat,
              size: 80.sp,
              color: AppColors.textGrey.withValues(alpha: 0.5),
            ),

            SizedBox(height: 24.h),

            MyText(
              text: 'Please log in to view messages',
              type: TextType.rubik,
              fontSize: 18.sp,
              fontWeight: FontWeight.w500,
              color: AppColors.textGrey,
              textAlign: TextAlign.center,
            ),

            SizedBox(height: 8.h),

            MyText(
              text: 'Connect with friends and start chatting',
              type: TextType.miSans,
              fontSize: 14.sp,
              color: AppColors.textGrey.withValues(alpha: 0.7),
              textAlign: TextAlign.center,
            ),

            SizedBox(height: 32.h),

            GestureDetector(
              onTap: () => context.push('/auth'),
              child: Container(
                width: double.infinity,
                padding: EdgeInsets.symmetric(vertical: 16.h),
                decoration: BoxDecoration(
                  color: AppColors.blue,
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: Center(
                  child: MyText(
                    text: "Go to Login",
                    type: TextType.miSans,
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w600,
                    color: AppColors.white,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _chuangjianBiaoqian(String wenzi, int suoyin) {
    bool dangqian = _dangqianYemian == suoyin;

    return Column(
      children: [
        GestureDetector(
          onTap: () {
            _yemianKongzhi.animateToPage(
              suoyin,
              duration: const Duration(milliseconds: 300),
              curve: Curves.easeInOut,
            );
          },
          child: MyText(
            text: wenzi,
            type: TextType.rubik,
            fontSize: 18.sp,
            fontWeight: dangqian ? FontWeight.bold : FontWeight.normal,
            color: dangqian ? AppColors.black : AppColors.textGrey,
          ),
        ),

        SizedBox(height: 8.h),
        Container(
          width: 24.w,
          height: 6.h,
          decoration: BoxDecoration(
            color: dangqian ? AppColors.blueSecond : Colors.transparent,
            borderRadius: BorderRadius.circular(2.r),
          ),
        ),
      ],
    );
  }

  Widget _chuangjianXiaoxiLiebiao() {
    return BlocBuilder<AuthCubit, AuthState>(
      builder: (context, authState) {
        if (!authState.isLoggedIn || authState.currentUser == null) {
          return Center(
            child: Padding(
              padding: EdgeInsets.only(top: 100.h),
              child: NoData(
                width: 200.w,
                height: 200.w,
                text: 'Please log in to view messages.',
              ),
            ),
          );
        }

        return BlocBuilder<ChatCubit, ChatState>(
          builder: (context, chatState) {
            if (chatState.isLoading) {
              return const Center(child: CircularProgressIndicator());
            }

            if (chatState.conversations.isEmpty) {
              return Center(
                child: Padding(
                  padding: EdgeInsets.only(top: 100.h),
                  child: NoData(
                    width: 200.w,
                    height: 200.w,
                    text: 'No messages yet.',
                  ),
                ),
              );
            }

            return FutureBuilder<List<_ConversationWithUser>>(
              future: _huoquHuihuaYuYonghu(chatState.conversations),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return const Center(child: CircularProgressIndicator());
                }

                if (snapshot.hasError) {
                  return Center(
                    child: Padding(
                      padding: EdgeInsets.only(top: 100.h),
                      child: NoData(
                        width: 200.w,
                        height: 200.w,
                        text: 'Failed to load conversations.',
                      ),
                    ),
                  );
                }

                final conversationsWithUsers = snapshot.data ?? [];

                return CustomScrollView(
                  slivers: [
                    SliverPadding(
                      padding: EdgeInsets.symmetric(
                        horizontal: 16.w,
                        vertical: 8.h,
                      ),
                      sliver: SliverList(
                        delegate: SliverChildBuilderDelegate((context, index) {
                          final item = conversationsWithUsers[index];
                          return _xiaoxiXiang(
                            xingming: item.user.name,
                            dizhi: item.lastMessage ?? 'No messages yet',
                            shijian: _formatTime(
                              item.conversation.lastActiveAt,
                            ),
                            touxiang: item.user.avatar,
                            onTap:
                                () => _openChat(
                                  authState.currentUser!.id,
                                  item.user.id,
                                ),
                          );
                        }, childCount: conversationsWithUsers.length),
                      ),
                    ),
                  ],
                );
              },
            );
          },
        );
      },
    );
  }

  Widget _chuangjianGuanzhuLiebiao() {
    return BlocBuilder<FollowCubit, FollowState>(
      builder: (context, followState) {
        if (followState.followingUserIds.isEmpty) {
          return Center(
            child: Padding(
              padding: EdgeInsets.only(top: 100.h),
              child: NoData(
                width: 200.w,
                height: 200.w,
                text: 'You haven\'t followed anyone yet.',
              ),
            ),
          );
        }

        return FutureBuilder<List<User>>(
          future: _huoquGuanzhuYonghu(followState.followingUserIds.toList()),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const Center(child: CircularProgressIndicator());
            }

            if (snapshot.hasError) {
              return Center(
                child: Padding(
                  padding: EdgeInsets.only(top: 100.h),
                  child: NoData(
                    width: 200.w,
                    height: 200.w,
                    text: 'Failed to load following users.',
                  ),
                ),
              );
            }

            final guanzhuYonghu = snapshot.data ?? [];

            if (guanzhuYonghu.isEmpty) {
              return Center(
                child: Padding(
                  padding: EdgeInsets.only(top: 100.h),
                  child: NoData(
                    width: 200.w,
                    height: 200.w,
                    text: 'You haven\'t followed anyone yet.',
                  ),
                ),
              );
            }

            return SingleChildScrollView(
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
              child: Column(
                children:
                    guanzhuYonghu
                        .map(
                          (user) => _guanzhuXiang(
                            xingming: user.name,
                            touxiang: user.avatar,
                            userId: user.id,
                          ),
                        )
                        .toList(),
              ),
            );
          },
        );
      },
    );
  }

  Future<List<User>> _huoquGuanzhuYonghu(List<String> userIds) async {
    final userData = UserData();
    final List<User> users = [];

    for (String userId in userIds) {
      final user = await userData.getUserById(userId);
      if (user != null) {
        users.add(user);
      }
    }

    return users;
  }

  Future<List<_ConversationWithUser>> _huoquHuihuaYuYonghu(
    List<ChatConversation> conversations,
  ) async {
    final userData = UserData();
    final chatData = ChatData();
    final List<_ConversationWithUser> result = [];

    final authState = context.read<AuthCubit>().state;
    if (authState.currentUser == null) return result;
    final currentUserId = authState.currentUser!.id;

    for (final conversation in conversations) {
      final otherUserId = conversation.getOtherUserId(currentUserId);

      final otherUser = await userData.getUserById(otherUserId);
      if (otherUser == null) continue;

      final lastMessage = await chatData.getLastMessage(conversation.id);

      result.add(
        _ConversationWithUser(
          conversation: conversation,
          user: otherUser,
          lastMessage: lastMessage?.content,
        ),
      );
    }

    return result;
  }

  String _formatTime(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inDays > 0) {
      return '${difference.inDays}d ago';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}h ago';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}min ago';
    } else {
      return 'now';
    }
  }

  void _openChat(String currentUserId, String otherUserId) {
    context.read<ChatCubit>().startConversationWithUser(
      currentUserId,
      otherUserId,
    );

    context.push('/message/chat');
  }

  Widget _xiaoxiXiang({
    required String xingming,
    required String dizhi,
    required String shijian,
    required String touxiang,
    VoidCallback? onTap,
  }) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 6.h),
      decoration: BoxDecoration(
        color: const Color(0xFFCDF3FA),
        borderRadius: BorderRadius.circular(16.r),
      ),
      child: ListTile(
        contentPadding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
        leading: CircleAvatar(
          radius: 24.r,
          backgroundImage: AssetImage(touxiang),
        ),
        title: MyText(
          text: xingming,
          type: TextType.rubik,
          fontSize: 16.sp,
          color: AppColors.black,
          fontWeight: FontWeight.w500,
        ),
        subtitle: MyText(
          text: dizhi,
          type: TextType.miSans,
          fontSize: 12.sp,
          color: Colors.black87,
          overflow: TextOverflow.ellipsis,
        ),
        trailing: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            MyText(
              text: shijian,
              type: TextType.miSans,
              fontSize: 12.sp,
              color: Colors.black54,
            ),
          ],
        ),
        onTap: onTap,
      ),
    );
  }

  Widget _guanzhuXiang({
    required String xingming,
    required String touxiang,
    required String userId,
  }) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 6.h),
      decoration: BoxDecoration(
        color: const Color(0xFFCDF3FA),
        borderRadius: BorderRadius.circular(16.r),
      ),
      child: ListTile(
        contentPadding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
        leading: CircleAvatar(
          radius: 24.r,
          backgroundImage: AssetImage(touxiang),
        ),
        title: MyText(
          text: xingming,
          type: TextType.rubik,
          fontSize: 16.sp,
          color: Colors.black,
          fontWeight: FontWeight.w500,
        ),
        trailing: IconButton(
          icon: const Icon(IconFontIcons.iconChat, color: Colors.black54),
          onPressed: () {
            final authState = context.read<AuthCubit>().state;
            if (authState.isLoggedIn && authState.currentUser != null) {
              _openChat(authState.currentUser!.id, userId);
            }
          },
        ),
        onTap: () {
          context.push('/profile/others/$userId');
        },
      ),
    );
  }
}
